/**
 * CEP Mobile on Android 2012 
 */
package com.orange.cepmanager.android.service;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.IBinder;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import com.orange.cepmanager.android.CEPManagerCommon;
import com.orange.cepmanager.android.esper.CEPManager;
import com.orange.cepmanager.android.listener.Listener;
import com.orange.cepmanager.android.listener.LocationListener;
import com.orange.cepmanager.android.ngsi.events.Event;

/**
 * The service launched a startup of application
 * 
 * @author gqxg9096 STAG FO
 * 
 */
public class Service extends android.app.Service {
	public static final String TAG = CEPManagerCommon.SERVICE_TAG;
	private static Service instance;
	private static boolean running;
	private boolean networkAvailable;
	private String androidDeviceId;

	// service instance
	public static Service getInstance() {
		return instance;
	}

	public Service() {
		super();
		// TODO Auto-generated constructor stub
		Log.i(TAG, "creating service");
		instance = this;
	}

	// service running
	public static boolean isRunning() {
		return running;
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	private static void setEnabled(final Context context,
			final boolean serviceEnabled) {
		final SharedPreferences prefs = context.getSharedPreferences(TAG,
				Context.MODE_PRIVATE);
		final Editor editor = prefs.edit();
		editor.putBoolean("serviceEnabled", serviceEnabled);
		editor.commit();
	}

	public static void start(final Context context, final boolean memorize) {
		if (memorize)
			setEnabled(context, true);
		context.startService(new Intent(context, Service.class));
	}

	public static void stop(final Context context, final boolean memorize) {
		if (memorize)
			setEnabled(context, false);
		context.stopService(new Intent(context, Service.class));
	}

	public static boolean isEnabled(final Context context) {
		final SharedPreferences prefs = context.getSharedPreferences(TAG,
				Context.MODE_PRIVATE);
		return prefs.getBoolean("serviceEnabled", false);
	}

	public boolean acceptIncomingEvent(final Event event) {
		if (!running || event == null)
			return false;
		if (androidDeviceId == null) {
			final TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
			androidDeviceId = telephonyManager.getSubscriberId();
		}
		event.deviceId = androidDeviceId != null ? androidDeviceId : "Unknown";
		if (event.timestamp == 0)
			event.timestamp = System.currentTimeMillis();
		Log.i(TAG, "event of geolocation " + event);
		if (CEPManagerCommon.sendEvent) {
			CEPManager.sendEvent(event);
			Toast.makeText(
					getApplicationContext(),
					"event send :** "+ event.params +"**", Toast.LENGTH_LONG).show();
		}

		return true;
	}

	private void registerListeners() {
		for (final Listener listener : new Listener[] { new LocationListener() })
			if (!listener.isRegistered())
				listener.register(this);
	}

	public static boolean checkPermissions(final Context context,
			final String[] neededPermissions) {
		for (final String permission : neededPermissions)
			if (context.checkCallingOrSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
				Log.e(TAG, "security error : requires " + permission
						+ " permission");
				return false;
			}
		return true;
	}

	private void startService() {
		Log.v(TAG, "starting service");
		registerListeners();
		running = true;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		startService();
	}

	@Override
	public void onDestroy() {
		shutdownService();
		super.onDestroy();
	}

	private void shutdownService() {
		Log.v(TAG, "ending service");
		running = false;
		// stop CEP
	}

	/*
	 * test connection
	 */
	private boolean checkNetwork() {
		boolean networkChanged = false;
		final ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity == null) {
			if (networkAvailable) {
				networkAvailable = false;
				networkChanged = true;
			}
		} else {
			final NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null)
				for (int i = 0; i < info.length; i++)
					if (info[i].getState() == NetworkInfo.State.CONNECTED)
						if (!networkAvailable) {
							networkAvailable = true;
							networkChanged = true;
						}
		}
		if (networkChanged)
			Log.v(TAG, "network availability has changed to : "
					+ networkAvailable);
		return networkChanged;
	}
}
